<?php

namespace api\modules\shop\controllers;

use common\models\GoodsAttr;
use common\models\SupplierGoods;
use common\models\SupplierGoodsImg;
use common\models\SupplierAttributeDeion;
use common\models\SupplierGoodsAttr;
use common\models\SupplierAttribute;
use common\models\SupplierAttributeValue;
use common\models\ShopCollection;

use common\service\ConstantService;
use common\service\GlobalUrlService;
use common\service\SupplierGoodsService;
class SupplierGoodsController extends ShopBaseController
{

    /**
     * 商品详情
     */
    public function actionGetGoodsInfo(){
        $id = $this->get('goods_id');
        $data = SupplierGoods::find()->where(['id'=>$id])->asArray()->one();
        if(!isset($data)){
            return $this->renderJson($data,'此商品不存在',ConstantService::$response_fail);
        }
        //浏览记录
        $collction_data['shop_id'] = $this->shop['id'];
        $collction_data['goods_id'] = $id;
        $collction_data['status'] = 0;
        $collction_data['is_del'] = 0;
        $collction_data['create_time'] = time();
        $collction_data['update_time'] = time();
        ShopCollection::addCollection($collction_data);
        $money = SupplierGoodsAttr::find()
            ->select('max(original_price) as max_original ,max(discount_price) as max_discount ,min(original_price) as min_original ,min(discount_price) as min_discount')
            ->where(['goods_id'=>$id])
            ->asArray()
            ->one();
        if(!empty($money)){
            $money['max_original'] = sprintf("%.2f",$money['max_original']);
            $money['max_discount'] = sprintf("%.2f",$money['max_discount']);
            $money['min_original'] = sprintf("%.2f",$money['min_original']);
            $money['min_discount'] = sprintf("%.2f",$money['min_discount']);
        }
        $data['money'] = $money;

        //是否收藏
        $data['is_collect'] = 0;
        $col = ShopCollection::find()->where(['shop_id'=>$this->shop['id'],'goods_id'=>$id,'status'=>1,'is_del'=>0])->asArray()->one();
        if(!empty($col)){
            $data['is_collect'] = $col['id'];
        }

        $data['list_img'] = GlobalUrlService::buildCdnUrl($data['list_img']);
        $imgs = SupplierGoodsImg::find()
            ->select('img_url')
            ->where(['goods_id'=>$data['id']])
            ->asArray()
            ->all();
        $data['imgs'] = $this->_SetGoodsImgCdn($imgs,'img_url');
        $data['freight'] = sprintf("%.2f",$data['freight']);
        return $this->renderJson($data,'',ConstantService::$response_success);
    }

    /**
     * 商品属性描述
     */
    public function actionGetAttrDeion(){
        $id = $this->get('goods_id');
        $data = SupplierAttributeDeion::find()
            ->select('key,val')
            ->where(['goods_id'=>$id])
            ->asArray()
            ->all();
        return $this->renderJson($data,'',ConstantService::$response_success);
    }

    /**
     * 商品属性
     */
    public function actionGetGoodsAttr(){
        $id = $this->get('goods_id');
        $attr = SupplierGoodsAttr::find()
            ->select('id,goods_id,original_price,discount_price,inventory,image,attribute_value_id')
            ->where(['goods_id'=>$id,'is_del'=>0])
            ->asArray()
            ->all();
        $attrvalId = [];
        foreach ($attr as $val){
            $attrval['attr_id'] = $val['id'];
            $valId = explode('-',$val['attribute_value_id']);
            $newvalId = [];
            foreach ($valId as $vid){
                if($vid != 0){
                    $newvalId[] = $vid;
                }
            }
            $attrvalId[] = $newvalId;
        }
        $count = count($attrvalId[0]);
        $resule['data'] = [];
        $newGoodsAttr = [];
        foreach ($attr as $val){
            $newGoodsAttr[$val['attribute_value_id']] = $val;
        }
        switch ($count){
            case 0:
                $attr[0]['attr_name'] = '';
                $attr[0]['value'] = '';
                $resule['data'][0]['list'] = $attr;
                $resule['data'][0]['name'] = '';
                $resule['type'] = 0;
                break;
            case 1:
                $one = array_column($attrvalId,0);
                $oneId = array_unique($one);
                $oneData = $this->_GetGoodsAttribute($oneId);
                $newTwo = [];
                foreach ($oneData as $val) {
                    $ids = $val['id'].'-0-0';
                    $GoodsAttrs = $newGoodsAttr[$ids];
                    $val['goods_id'] = $id;
                    $val['discount_price'] = 0;
                    $val['original_price'] = 0;
                    $val['inventory'] = 0;
                    $val['image'] = '';
                    $val['attribute_value_id'] = '';
                    if(!empty($GoodsAttrs)){
                        $val['id'] = $GoodsAttrs['id'];
                        $val['goods_id'] = $GoodsAttrs['goods_id'];
                        $val['discount_price'] = $GoodsAttrs['discount_price'];
                        $val['original_price'] = $GoodsAttrs['original_price'];
                        $val['inventory'] = $GoodsAttrs['inventory'];
                        $val['image'] = GlobalUrlService::buildCdnUrl($GoodsAttrs['image']);
                        $val['attribute_value_id'] = $GoodsAttrs['attribute_value_id'];
                    }
                    $newTwo[] = $val;
                }
                $resule['type'] = 1;
                $resule['data'][0]['name'] = $oneData[0]['attr_name'];
                $resule['data'][0]['list'] = $newTwo;
                break;
            case 2:
                $one = array_column($attrvalId,0);
                $two = array_column($attrvalId,1);
                $oneId = array_unique($one);
                $twoId = array_unique($two);
                $oneData = $this->_GetGoodsAttribute($oneId);
                $twoData = $this->_GetGoodsAttribute($twoId);
                $newData = [];
                foreach ($oneData as $val){
                    $Temp['name'] = $val['value'];
                    $newTwo = [];
                    foreach ($twoData as $row){
                        $ids = $val['id'].'-'.$row['id'].'-0';
                        $GoodsAttrs = $newGoodsAttr[$ids];
                        $row['goods_id'] = $id;
                        $row['discount_price'] = 0;
                        $row['original_price'] = 0;
                        $row['inventory'] = 0;
                        $row['image'] = '';
                        $row['attribute_value_id'] = '';
                        if(!empty($GoodsAttrs)){
                            $row['id'] = $GoodsAttrs['id'];
                            $row['goods_id'] = $GoodsAttrs['goods_id'];
                            $row['discount_price'] = $GoodsAttrs['discount_price'];
                            $row['original_price'] = $GoodsAttrs['original_price'];
                            $row['inventory'] = $GoodsAttrs['inventory'];
                            $row['image'] = GlobalUrlService::buildCdnUrl($GoodsAttrs['image']);
                            $row['attribute_value_id'] = $GoodsAttrs['attribute_value_id'];
                        }
                        $newTwo[] = $row;
                    }
                    $Temp['list'] = $newTwo;
                    $newData[] = $Temp;
                }
                $resule['data'] = $newData;
                $resule['type'] = 2;
        }
        return $this->renderJson($resule,'',ConstantService::$response_success);
    }


    /**
     * 查看更多
     * type 0商品详情页   1更多商品/搜索结果
     * goods_type 0普通 2推荐 3热门 4新品 5 折扣
     * sort_type 1销量 2 价格高到低  3 价格低到高
     */
    public function actionGetGoodsList(){
        //排序默认1销量 2 价格高到低  3 价格低到高
        $id = $this->get('goods_id')?$this->get('goods_id'):0;
        $type = $this->get('type')?$this->get('type'):0;
        $sort_type = $this->get('sort_type')?$this->get('sort_type'):0;
        $goods_type = $this->get('goods_type')?$this->get('goods_type'):0;
        $goods_name = $this->get('goods_name')?$this->get('goods_name'):'';
        $tree_id = $this->get('tree_id')?$this->get('tree_id'):0;

        $goodsDb = SupplierGoods::find();
        if($goods_type) {
            $goodsDb->andWhere(['goods_type' => $goods_type]);
        }
        $goodsDb->andWhere(['is_del' => 0]);
        $goodsDb->andWhere(['status' => 1]);
        if(!empty($goods_name)){
            $goodsDb->andWhere(['like' ,'goods_name',$goods_name]);
        }
        //更多商品
        if($type > 0) {
            switch ($sort_type) {
                case 0:
                    $order = ['id' => SORT_DESC];
                    break;
                case 1:
                    $order = ['sales_volume' => SORT_DESC];
                    break;
                case 2:
                    $order = ['max_price' => SORT_DESC];
                    break;
                case 3:
                    $order = ['min_price' => SORT_ASC];
                    break;
                default;
            }
            if($tree_id > 0){
                $goodsDb->andWhere(['three_tree_id'=>$tree_id]);
            }
            $p = intval($this->get('page', 1));
            $p = ($p > 0) ? $p : 1;

            $offset = ($p - 1) * $this->page_size;
            $goodsDb->limit($this->page_size);
            $goodsDb->orderBy($order);
            $goodsDb->offset($offset);
        } else {
            $goodsDb->andWhere(['!=','id',$id]);
        }
        $data = $goodsDb
            ->asArray()
            ->all();
        //商品详情
        if($type == 0){
            if(count($data) > 6){
                $temp = array_rand($data, 6);
                foreach ($temp as $val) {
                    $data_last[] = $data[$val];
                }
                unset($val);
            } else {
                $limit = 6-count($data);
                $newId = array_column($data,'id');
                $goodsDb = SupplierGoods::find();
                $goodsDb->andWhere(['is_del' => 0]);
                $newId = array_merge($newId,(array)$id);

                if(!empty($newId)){
                    $goodsDb->andWhere(['not in','id',$newId]);
                }

                $data_last = $goodsDb->limit($limit)
                    ->asArray()
                    ->all();

                $data_last = array_merge($data,$data_last);

            }

            $data = $data_last;
        }
        $data = SupplierGoodsService::GetAttrListPrice($data);
        return $this->renderJson($data,'',ConstantService::$response_success);
    }



    private function _GetGoodsAttribute($id){
        $attribute = SupplierAttributeValue::find()
            ->select('id,attr_name,value')
            ->where(['id'=>$id])
            ->asArray()
            ->all();
        return $attribute;
    }

    /**
     * 设置图片img
     * @param $data
     * @return mixed
     */
    private function _SetGoodsImgCdn($data,$key){
        foreach ($data as &$val){
            $val[$key] = GlobalUrlService::buildCdnUrl($val[$key]);
        }
        return $data;
    }
}